package com.flex.core.utils;



/*
 *
 * Original Author: airland.congs
 * Campany: Disport Support Group (AT) JoyGogo
 * Copyright 2005, by JoyGogo Beijing Research Branch.
 * 
 *
 * Changes
 * ---------
 *
 * 
 */

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 
 * 此类是MD5加密算法的实现， 采用了java内置算法，需要引用java.security.MessageDigest
 * 
 * @author airland.congs
 * @version $Revision: 1.1 $
 * 
 */
public class MD5Util {
	// 小写的字符串
	private static char[] DigitLower = { '0', '1', '2', '3', '4', '5', '6',
			'7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

	// 大写的字符串
	private static char[] DigitUpper = { '0', '1', '2', '3', '4', '5', '6',
			'7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };

	/**
	 * 默认构造函数
	 * 
	 */
	public MD5Util() {
	}

	/**
	 * 加密之后的字符串全为小写
	 * 
	 * @param srcStr
	 * @return
	 * @throws NoSuchAlgorithmException
	 * @throws NullPointerException
	 */
	public static String getMD5Lower(String srcStr)
			throws NoSuchAlgorithmException, NullPointerException {
		String sign = "lower";
		return processStr(srcStr, sign);

	}

	private static String processStr(String srcStr, String sign)
			throws NoSuchAlgorithmException, NullPointerException {
		if (null == srcStr) {
			throw new java.lang.NullPointerException("需要加密的字符串为Null");
		}

		MessageDigest digest;

		// 定义调用的方法
		String algorithm = "MD5";

		// 结果字符串
		String result = "";
		// 初始化并开始进行计算
		digest = MessageDigest.getInstance(algorithm);
		digest.update(srcStr.getBytes());

		byte[] byteRes = digest.digest();

		// 计算byte数组的长度
		int length = byteRes.length;

		// 将byte数组转换成字符串
		for (int i = 0; i < length; i++) {
			result = result + byteHEX(byteRes[i], sign);
		}

		return result;
	}

	/**
	 * 将btye数组转换成字符串
	 * 
	 * @param bt
	 * @return
	 */
	private static String byteHEX(byte bt, String sign) {

		char[] temp = null;
		if (sign.equalsIgnoreCase("lower")) {
			temp = DigitLower;
		} else if (sign.equalsIgnoreCase("upper")) {
			temp = DigitUpper;
		} else {
			throw new java.lang.NullPointerException("加密缺少必要的条件");
		}
		char[] ob = new char[2];

		ob[0] = temp[(bt >>> 4) & 0X0F];

		ob[1] = temp[bt & 0X0F];

		return new String(ob);

	}

}